package com.haois.mp.wechat.handler;

import com.haois.mp.wechat.common.BusinessRemind;
import com.haois.mp.database.module.basic.util.SpringContextHolder;
import com.haois.mp.database.commom.enums.MpTypeEnum;
import com.haois.mp.database.module.common.daomain.Parameter;
import com.haois.mp.database.module.common.daomain.UserToken;
import com.haois.mp.database.module.remote.service.IUserService;
import com.haois.mp.database.module.sdk.api.ItpkService;
import com.haois.mp.database.module.common.service.IUserTokenService;
import com.haois.mp.database.module.wxserver.service.EventHandlerService;
import com.haois.mp.database.util.ReflectUtil;
import com.haois.mp.wechat.constants.Enum.MenuEnum;
import com.haois.mp.wechat.constants.UrlConstants;
import com.haois.mp.wechat.server.AbstractMoreInfoServer;
import com.haois.mp.wechat.server.MoreInfoServerImpl;
import com.haois.mp.wechat.server.QuickSearchServerImpl;
import com.haois.mp.wechat.util.WxUtil;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by RuiHaoZ on 2017/12/8.
 */
@Component
public class TextHandler extends AbstractHandler implements WxMpMessageHandler {

    @Value("${defined.wxmp.base-url}")
    private String baseUrl;
    @Value("${defined.wxmp.sys-openid}")
    private String sysOpenId;

    @Autowired
    protected IUserService iUserService;
    @Autowired
    protected IUserTokenService iUserTokenService;
    @Autowired
    private EventHandlerService eventHandlerService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map, WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException {

        String content = this.execute(wxMpXmlMessage, wxMpService);
        if (content.equals("success")) {
            return null;
        } else {
            return WxMpXmlOutMessage.TEXT()
                    .fromUser(wxMpXmlMessage.getToUser())
                    .toUser(wxMpXmlMessage.getFromUser())
                    .content(content).build();
        }
    }

    @Override
    public String execute(WxMpXmlMessage wxMpXmlMessage, WxMpService wxMpService) {
        String content = "";
        try {
            String openId = wxMpXmlMessage.getFromUser();
            String wxMsg = wxMpXmlMessage.getContent();
            UserToken userToken = iUserTokenService.findByOpenId(openId, MpTypeEnum.OFFACCOUNTS.getType());
            if (userToken == null) {
                String url = UrlConstants.INFO_LOGIN_URL;
                url = WxUtil.transferWxUrl(wxMpService, url, MenuEnum.BTN_INFO_LOGIN.getKey(), baseUrl);
                content = "<a href=\"" + url + "\">你未登录，请先绑定账号</a>";
                return content;
            }
            String eventKey = eventHandlerService.queryLatelyEvent(wxMpXmlMessage.getFromUser());
            if (StringUtils.isNotEmpty(eventKey) && "Q".equals(wxMsg.toUpperCase())) {
                eventHandlerService.deleteEvent(openId);
                content = "您已退出更多服务模式";
            } else if (StringUtils.isEmpty(eventKey) && wxMsg.startsWith("转发 ")) {
                content = "转发消息功能，请先点击菜单更多服务激活(五分钟内有效，退出请发送:Q)";
            } else {
                if (MenuEnum.BTN_INFO_QUICK.getKey().equals(eventKey)) {
                    AbstractMoreInfoServer moreInfoServer = SpringContextHolder.getBean(QuickSearchServerImpl.class);
                    content = moreInfoServer.execute(wxMpXmlMessage);
                } else if (MenuEnum.BTN_INFO_MORE.getKey().equals(eventKey)) {
                    Parameter parameter = eventHandlerService.getParByContAndKey(wxMsg.split(" ")[0], Parameter.BT);
                    if (parameter != null) {
                        AbstractMoreInfoServer moreInfoServer = SpringContextHolder.getBean(ReflectUtil.getClassName(parameter.getMethod()));
                        content = moreInfoServer.executePlus(wxMpXmlMessage, userToken);
                    } else {
                        AbstractMoreInfoServer moreInfoServer = SpringContextHolder.getBean(MoreInfoServerImpl.class);
                        content = moreInfoServer.execute(wxMpXmlMessage);
                    }
                } else if (MenuEnum.BTN_AI_CHAT.getKey().equals(eventKey)) {
                    content = ItpkService.question(wxMsg);
                } else {
                    content = "\ue115\ue115\ue115";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            content = "服务异常，请稍候再试";
            BusinessRemind.remindErrorByWx(wxMpXmlMessage.getFromUser(), e.getMessage(), sysOpenId, this.getClass().getName());
        }
        return content;
    }

}

